import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:shining_red_star/model/router_params.dart';
import 'package:shining_red_star/utils/play.dart';
import '../../api/list_letter.dart';
import '../../model/pin_yin.dart';
import '../../utils/focus.dart';
import '../../widgets/letter_card.dart';
import '../../wrappers/safe-area.dart';

class PinYinDetailPage extends StatefulWidget {
  const PinYinDetailPage({super.key});

  @override
  State<PinYinDetailPage> createState() => _PinYinDetailPageState();
}

class _PinYinDetailPageState extends State<PinYinDetailPage> {
  SwiperController controller = SwiperController();
  FocusScopeNode focusScopeNode = FocusScopeNode();
  FocusNode focusNode = FocusNode();
  int currentIndex = 0;
  List<LetterInfo> letterList = [];

  void playAud(int index) {
    if (letterList.isEmpty) {
      return;
    }
    AudioPlayManager.lowLatencyPlay(letterList[index].aud);
  }

  Future<CommonDetailRouterArguments> getRouterArguments() {
    Completer<CommonDetailRouterArguments> completer = Completer();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      CommonDetailRouterArguments? args = ModalRoute.of(context)
          ?.settings
          .arguments as CommonDetailRouterArguments?;
      completer.complete(args ?? CommonDetailRouterArguments());
    });
    return completer.future;
  }

  @override
  void initState() {
    super.initState();
    Future.wait([getRouterArguments(), listLetter()]).then((res) {
      CommonDetailRouterArguments routerArguments =
          res[0] as CommonDetailRouterArguments;
      List<LetterInfo> list = res[1] as List<LetterInfo>;
      if (routerArguments.group != null) {
        List<LetterInfo> tmpList = [];
        for (var item in list) {
          if (item.group.contains(routerArguments.group)) {
            tmpList.add(item);
          }
        }
        list = tmpList;
      }
      setState(() {
        letterList = list;
        currentIndex = max(
            list.indexWhere(
                (item) => item.value.toString() == routerArguments.id),
            0);
        playAud(currentIndex);
      });
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PopScope(
        canPop: false,
        onPopInvokedWithResult: (didPop, result) {
          if (didPop) {
            return;
          }
          if (hasChildFocus(focusScopeNode)) {
            focusScopeNode.focusedChild?.unfocus();
            return;
          }
          Navigator.of(context).pop();
        },
        child: SafeAreaPageWrapper(
          padding: EdgeInsets.all(12),
          child: letterList.isEmpty
              ? Center(
                  child: Text('数据加载中'),
                )
              : FocusScope(
                  node: focusScopeNode,
                  autofocus: true,
                  onKeyEvent: (node, event) {
                    if (event is KeyDownEvent) {
                      switch (event.logicalKey) {
                        case LogicalKeyboardKey.arrowLeft:
                          if (hasChildFocus(focusScopeNode)) {
                            focusScopeNode
                                .focusInDirection(TraversalDirection.left);
                          } else {
                            controller.previous();
                          }
                          return KeyEventResult.handled;
                        case LogicalKeyboardKey.arrowRight:
                          if (hasChildFocus(focusScopeNode)) {
                            focusScopeNode
                                .focusInDirection(TraversalDirection.right);
                          } else {
                            controller.next();
                          }
                          return KeyEventResult.handled;
                        case LogicalKeyboardKey.arrowUp:
                          if (hasChildFocus(focusScopeNode)) {
                            focusScopeNode
                                .focusInDirection(TraversalDirection.up);
                          } else {
                            controller.previous();
                          }
                          return KeyEventResult.handled;
                        case LogicalKeyboardKey.arrowDown:
                          if (hasChildFocus(focusScopeNode)) {
                            focusScopeNode
                                .focusInDirection(TraversalDirection.down);
                          } else {
                            controller.next();
                          }
                          return KeyEventResult.handled;
                        case LogicalKeyboardKey.enter:
                        case LogicalKeyboardKey.select:
                          if (!hasChildFocus(focusScopeNode)) {
                            focusNode.requestFocus();
                            playAud(currentIndex);
                            return KeyEventResult.handled;
                          }
                      }
                    }
                    return KeyEventResult.ignored;
                  },
                  child: Swiper(
                    index: currentIndex,
                    itemCount: letterList.length,
                    controller: controller,
                    scrollDirection: Axis.vertical,
                    onTap: (index) {
                      playAud(index);
                    },
                    itemBuilder: (BuildContext context, int index) {
                      MediaQueryData metaQueryData = MediaQuery.of(context);
                      Orientation orientation = metaQueryData.orientation;
                      Size size = metaQueryData.size;
                      List<Tone> toneList = letterList[index].toneList;
                      double maxSize = min(size.width, size.height);
                      List<Widget> list = [
                        SizedBox(
                            width: maxSize,
                            height: maxSize,
                            child: Center(
                              child: LetterCard(
                                focusNode: focusNode,
                                value: letterList[index].value,
                                onConfirm: () {
                                  AudioPlayManager.lowLatencyPlay(letterList[index].aud);
                                },
                              ),
                            )),
                      ];

                      if (toneList.isNotEmpty) {
                        list.addAll([
                          SizedBox(width: 60, height: 60),
                          Expanded(
                              child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Row(
                                children: [
                                  Flexible(
                                      child: LetterCard(
                                    value: toneList[0].value,
                                    onConfirm: () {
                                      AudioPlayManager.lowLatencyPlay(toneList[0].aud);
                                    },
                                  )),
                                  SizedBox(width: 12),
                                  Flexible(
                                      child: LetterCard(
                                    value: toneList[1].value,
                                    onConfirm: () {
                                      AudioPlayManager.lowLatencyPlay(toneList[1].aud);
                                    },
                                  )),
                                ],
                              ),
                              SizedBox(height: 60),
                              Row(
                                children: [
                                  Flexible(
                                      child: LetterCard(
                                    value: toneList[2].value,
                                    onConfirm: () {
                                      AudioPlayManager.lowLatencyPlay(toneList[2].aud);
                                    },
                                  )),
                                  SizedBox(width: 12, height: 12),
                                  Flexible(
                                      child: LetterCard(
                                    value: toneList[3].value,
                                    onConfirm: () {
                                      AudioPlayManager.lowLatencyPlay(toneList[3].aud);
                                    },
                                  )),
                                ],
                              )
                            ],
                          ))
                        ]);
                      }

                      if (orientation == Orientation.portrait) {
                        return Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: list,
                        );
                      }

                      return Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: list,
                      );
                    },
                    onIndexChanged: (index) {
                      setState(() {
                        currentIndex = index;
                      });
                      playAud(index);
                      if (hasChildFocus(focusScopeNode)) {
                        focusScopeNode.focusedChild?.unfocus();
                        return;
                      }
                    },
                  ),
                ),
        ));
  }
}
